import json

from DarlingTestTools.settings import logger
from DataFactory.common import mysql_conn
import requests


class CheckDashboardQuotation:

    def __init__(self):
        self.logger = logger
        self.session = requests.session()
        self.header = {
            "Content-Type": "application/json",
            "countryId": 1001
        }

    def check_all_chat_quotation_not_answered_after_30_minutes(self, env, host, countryID, token_needed):
        global dashboard_data
        self.header["countryId"] = countryID
        try:
            self.header['token'] = token_needed
            dashboard_result = self.session.get(
                url=host + "/soundwave/report/web/dashboard",
                header=self.header
            )
            if dashboard_result.status_code != 200 and "200" != json.loads(dashboard_result.content)['code']:
                self.logger.error("Can not get CS/CA list, please check service!")
                return None
            elif "200" != json.loads(dashboard_result.content)['code']:
                self.logger.error("Can not get CS/CA list.")
                return None
            elif not json.loads(dashboard_result.content)['data']:
                self.logger.error("Can not get CS/CA list.")
                return None
            else:
                dashboard_data = json.loads(dashboard_result.content)["data"]["quotationVOList"]
        except Exception as e:
            self.logger.error(e)

        if dashboard_data:
            if len(dashboard_data) != 2:
                self.logger.error("Quotation data is wrong! --> " + str(dashboard_data))
            else:
                for use_data in dashboard_data:
                    if len(use_data.keys) < 1:
                        self.logger.error("Quotation data is null!\n" + str(dashboard_data))
                    else:
                        if use_data["key"] == "Non-Insurance":
                            customer_number = use_data["notAnsweredAfter30MinQuotationNum"]
                            self.logger.info("Customer number from interFace is : " + str(customer_number))
                            sql_script = '''SELECT
                                                DISTINCT aa.from_account
                                            FROM
                                                imserver.im_message aa 
                                            WHERE
                                                DATE_ADD( aa.create_time, INTERVAL 15 DAY ) > NOW( ) 
                                                AND aa.conv_type = "TEAM" 
                                                AND aa.from_account NOT IN (
                                                SELECT
                                                    bb.yunxin_acc_id 
                                                FROM
                                                    imserver.im_account_customer_service_staff bb 
                                                WHERE
                                                    bb.cs_staff_type = 3 
                                                ) 
                                                AND DATE_ADD( aa.create_time, INTERVAL 30 MINUTE ) < NOW( ) 
                                                AND aa.from_account LIKE "customer_%";'''
                            try:
                                conn = mysql_conn.get_cur(env)["conn"]
                                cur = mysql_conn.get_cur(env)["cur"]
                                cur.execute(sql_script)
                                data = cur.fetchall()
                                if len(data) == 0:
                                    logger.error("Can not get chat message.")
                                else:
                                    logger.info("Customer list : ")
                                conn.commit()
                            except Exception as e:
                                self.logger.error(e)
                        elif use_data["key"] == "Insurance":
                            pass
                        else:
                            self.logger.error("Quotation data is unknown : " + str(use_data))
